package com.huang.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.eduorder.component.CourseContant;
import com.huang.eduorder.entity.Order;
import com.huang.eduorder.entity.SkillCourse;
import com.huang.eduorder.service.OrderService;
import com.huang.servicebase.execptionhandler.huangException;
import com.hunag.utils.JwtUtils;
import com.hunag.utils.R;
import com.hunag.utils.orderVo.EduCourseOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-04-03
 */
@RestController
@RequestMapping("/eduorder/order")
public class OrderController {

    @Autowired
    private OrderService service;


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    //同步发送订单
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        System.out.println(id);
        if (StringUtils.isEmpty(id)) {
            throw new huangException(20001, "获取不到id");
        }
        String orderNo = service.createOrder(courseId, id);
        return R.ok().data("orderNo", orderNo);
    }


    //异步下单
    @PostMapping("/sendOrderMessage")
    public R topicSendMessage(@RequestBody SkillCourse skillCourse,HttpServletRequest request) throws Exception {
        Order order =null;
        String id = JwtUtils.getMemberIdByJwtToken(request);
        if (!StringUtils.isEmpty(id)) {
            order =service.createOrder2(id, skillCourse);

        } else {
            throw new huangException(20001, "当前没有用户，亲先登录");
        }


        return R.ok().data("order",order);
    }




    //根据订单Id获取订单的信息
    @GetMapping("getOrderInfo/{id}")
    public R getOrderInfo(@PathVariable String id) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Order order = service.getOne(wrapper);
        return R.ok().data("item", order);
    }

    //查询是否购买
    @GetMapping("isBuy/{memberId}/{courseId}")
    public boolean isBuy(@PathVariable String memberId, @PathVariable String courseId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", memberId);
        wrapper.eq("course_Id", courseId);
        wrapper.eq("status", 1);
        Integer count = service.count(wrapper);
        if (count > 0) {
            return true;
        }
        return false;

    }

    // 点击付款  修改状态 
    @GetMapping("/updateStatus/{orderId}")
    public boolean updateStatus(@PathVariable String orderId){

        service.updateStatus(orderId);
      return true;

    }

    @PostMapping("/getBuyList")
    public R getBuyList(HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        List<EduCourseOrder> res=service.getBuyList(memberId);
      return R.ok().data("BuyList",res);
    }

    //  后台添加秒杀课程  入redis
    @PostMapping("/addSkillCourse/{time}")
    public String addSkillCourse(@PathVariable("time") String time,@RequestBody SkillCourse eduCourse){
        String key=null;
        try {
            key= CourseContant.PRODUCT_KILL+eduCourse.getCourseId();
           int secound=Integer.parseInt(time);
            redisTemplate.opsForValue().set(key,eduCourse,secound, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return key;
    }

     // 查询redis中的 所有正在营销的课程
    @GetMapping("/getSkillListOnRedis")
    public R getSkilList(){
        String  prefix=CourseContant.PRODUCT_KILL+"*";
        Set<String> keys = redisTemplate.keys(prefix);
        List<Object> skillList =redisTemplate.opsForValue().multiGet(keys);
        List<SkillCourse> res = (List) skillList;
        return R.ok().data("skillList",res);
    }
    //下架
    @DeleteMapping("/downSkill/{courseId}")
    public R downSkill(@PathVariable String courseId){
        String key = CourseContant.PRODUCT_KILL + courseId;
        Boolean delete = redisTemplate.delete(key);
        return R.ok().data("flag",delete);
    }

    @GetMapping("/addCount/{courseId}/{count}")
    public R addCount(@PathVariable String courseId,@PathVariable Integer count){
        try {
            String key = CourseContant.PRODUCT_KILL + courseId;
            SkillCourse course = (SkillCourse) redisTemplate.opsForValue().get(key);
            course.setCount(course.getCount()+count);
            redisTemplate.opsForValue().set(key,course,
                    redisTemplate.opsForValue().getOperations().getExpire(key), TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("flag",false);
        }
        return  R.ok().data("flag",true);
    }
}

